package com.dragon.modules.yuegou.service.impl.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.modules.yuegou.entity.system.AddressEntity;
import com.dragon.modules.yuegou.mapper.system.AddressMapper;
import com.dragon.modules.yuegou.model.system.Address;
import com.dragon.modules.yuegou.query.system.AddressQuery;
import com.dragon.modules.yuegou.service.system.AddressService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 地址 服务实现
 *
 * @author pbuilder generated
 * @date 2019-03-19 08:59:41
 * @version 2.0
 */
@Service("sysAddressService")
public class AddressServiceImpl extends ServiceImpl<AddressMapper, AddressEntity> implements AddressService {

	@Override
	public List<Address> province() {
		AddressQuery addressQuery = new AddressQuery();
		addressQuery.setLevel("province");
		QueryWrapper<AddressEntity> qw = addressQuery.toQueryWrapper();
		qw.orderByAsc(Address.COL_ADCODE);

		List<AddressEntity> entities = baseMapper.selectList(qw);

		return entities.stream().map(Address::new).collect(Collectors.toList());
	}

	@Override
	public List<Address> city(String provinceId) {
		AddressQuery addressQuery = new AddressQuery();
		addressQuery.id().like(provinceId.substring(0, provinceId.length()-8)+"____0000");

		QueryWrapper<AddressEntity> qw = addressQuery.toQueryWrapper();
		qw.orderByAsc(Address.COL_ADCODE);

		List<AddressEntity> entities = baseMapper.selectList(qw);
		List<Address> list =entities.stream().map(Address::new).collect(Collectors.toList());
		removeList(provinceId,list);
		return list;
	}

	@Override
	public List<Address> area(String cityId) {
		AddressQuery addressQuery = new AddressQuery();
		addressQuery.id().like(cityId.substring(0, cityId.length()-4)+"____");
		QueryWrapper<AddressEntity> qw = addressQuery.toQueryWrapper();
		qw.orderByAsc(Address.COL_ADCODE);

		List<AddressEntity> entities = baseMapper.selectList(qw);
		List<Address> list =entities.stream().map(Address::new).collect(Collectors.toList());
		removeList(cityId,list);
		return list;
	}

	@Override
	public Address getByName(String name) {
		AddressQuery addressQuery = new AddressQuery();
		addressQuery.setName(name);
		QueryWrapper<AddressEntity> qw = addressQuery.toQueryWrapper();
		qw.orderByAsc(Address.COL_ADCODE);

		List<AddressEntity> entities = baseMapper.selectList(qw);
		if (CollectionUtils.isEmpty(entities)){
			return null;
		}
		return new Address(entities.get(0));
	}

	private void removeList(String id,List<Address> list) {
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getId().equals(id)) {
				list.remove(list.get(i));
			}
		}
	}

}